﻿using Caching;
using Helpers;
using SmallJob.Model;
using SmallJob.Services.Code;
using SmallJob.Services.Implements;
using SmallJob.Services.Interfaces;
using SmallShop.Services.Code;
using SmallShop.Services.Implements;
using SmallShop.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FrontEnd.Controllers
{
    public class OrderController : Controller
    {
        //
        // GET: /Order/
        private readonly ICategoryService _CategoryService;

        private readonly IProvideService _ProvideService;
        private readonly IUserService _UserService;
        private readonly ISkillService _SkillService;
        private readonly IBannerService _BannerService;
        private readonly IMMessageService _MMessageService;
        private readonly IOrderService _OrderService;
        private readonly IEmailFormatService _EmailFormatService;
        private readonly IRequestService _RequestService;
        private readonly IBidRequestService _BidRequestService;
        private readonly ISmsLogService _SmsLogService;
        private readonly IMConversationService _MConversationService;

        public OrderController(ICategoryService CategoryService, IProvideService ProvideService, IUserService UserService, ISkillService SkillService, IBannerService BannerService, IMMessageService MMessageService, IOrderService OrderService, IEmailFormatService EmailFormatService, IRequestService RequestService, IBidRequestService BidRequestService, ISmsLogService SmsLogService, IMConversationService MConversationService)
        {
            this._CategoryService = CategoryService;
            this._ProvideService = ProvideService;
            this._UserService = UserService;
            this._SkillService = SkillService;
            this._BannerService = BannerService;
            this._MMessageService = MMessageService;
            this._OrderService = OrderService;
            this._EmailFormatService = EmailFormatService;
            this._RequestService = RequestService;
            this._BidRequestService = BidRequestService;
            this._SmsLogService = SmsLogService;
            _MConversationService = MConversationService;
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Save(int orderid, string contentMessage)
        {
            if (!User.Identity.IsAuthenticated) return RedirectToAction("index", "home");
            var user = UtilityService.GetLoginUser(_UserService, User);
            var order = _OrderService.GetById(orderid);
            if (!string.IsNullOrWhiteSpace(contentMessage))
            {
                MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, contentMessage, MessageHelper.BuildShortIDOrder(orderid), OrderHelper.GetWorkerID(order), OrderHelper.GetPayerID(order), (int)MessageType.ORDER_PROVIDE, null);
                var unread = _MMessageService.CountUnread(OrderHelper.GetWorkerID(order));
                MessageHelper.SendMessageNotifyMessage(_MMessageService, Resources.Resource.SystemNotifyQuestion, unread, Resources.Resource.NumberMessageToNotify, OrderHelper.GetWorkerID(order), false);
            }
            return Json(new { sellerID = OrderHelper.GetWorkerID(order), buyerId = user.ID, buyerName = user.ProperName });
            //return RedirectToAction("Details", "Provide", new { id = order.ProvideID });
        }

        public ActionResult SaveBidRequest(int requestID, int sellerID, string contentMessage, int priceBid)
        {
            if (!User.Identity.IsAuthenticated) return RedirectToAction("index", "home");
            string firstMessage = Resources.Resource.SystemMessageBid.Replace("{price}", (priceBid * 1000).ToString());
            var user = _UserService.GetByFBID(User.Identity.Name) ?? _UserService.GetByEmail(User.Identity.Name);
            BidRequest o = new BidRequest()
            {
                BidderID = user.ID,
                SellerID = sellerID,
                RequestID = requestID,
                ModifiedDate = DateTime.Now,
                CreatedDate = DateTime.Now,
                PriceBid = priceBid * 1000,
                IsDeleted = false,
                IsSuccess = false
            };
            _BidRequestService.Add(o);
            MMessage m = new MMessage()
            {
                Content = firstMessage,
                Date = DateTime.Now,
                IsRead = false,
                ParentID = MessageHelper.BuildShortIDRequest(requestID, user.ID),
                ReceiverID = sellerID,
                SenderID = user.ID,
                Type = (int)MessageType.REQUEST
            };
            _MMessageService.Add(m);
            var lastmes = m;
            if (!string.IsNullOrWhiteSpace(contentMessage))
            {
                MMessage m2 = new MMessage()
                {
                    Content = contentMessage,
                    Date = DateTime.Now,
                    IsRead = false,
                    ParentID = MessageHelper.BuildShortIDRequest(requestID, user.ID),
                    ReceiverID = sellerID,
                    SenderID = user.ID,
                    Type = (int)MessageType.REQUEST
                };
                _MMessageService.Add(m2);
                lastmes = m2;
            }
            var seller = _UserService.GetById(sellerID);
            var cvs = _MConversationService.GetConversationByShortID(m.ParentID);
            if (cvs == null)
            {
                cvs = new MConversation()
                {
                    Person1ID = sellerID,
                    Person2ID = user.ID,
                    ShortID = MessageHelper.BuildShortIDRequest(requestID, user.ID),
                    Type = (int)MessageType.REQUEST,
                    User1 = MongoConvert.ConvertUser(seller),
                    User2 = MongoConvert.ConvertUser(user),
                    Request = MongoConvert.ConvertRequest(_RequestService.GetById(requestID))
                };
                _MConversationService.Add(cvs);
            }
            cvs.Message = lastmes;
            _MConversationService.Update(cvs);
            var rq = _RequestService.GetById(requestID);
            //send notify
            EmailFormat format = null;
            DictionaryMessageBid dic = null;
            try
            {
                format = _EmailFormatService.GetById(Convert.ToInt32(Resources.Resource.NotifyEmailBidding));
                var email = UserUtility.GetVerifiedEmail(seller);
                dic = new DictionaryMessageBid(email, user.ProperName, rq.Title, cvs.ShortID, o.PriceBid.ToString());
                UserUtility.NotifyEmail(format, dic);

                var notifyFormat = Resources.Resource.SystemNotifyMessageBid;
                var contentNotify = MessageHelper.BuildNotifyMessageContent(notifyFormat, dic);
                MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, contentNotify, MessageHelper.BuildShortIDNotify(m.ParentID), m.ReceiverID, m.SenderID, (int)MessageType.System_Notify, null);
            }
            catch (Exception) { }

            if (!string.IsNullOrWhiteSpace(rq.ForwardEmail))
            {
                try
                {
                    format = _EmailFormatService.GetById(Convert.ToInt32(Resources.Resource.NotifyEmailForwardMessage));
                    var dicmes = new DictionaryForwardMessage(rq.ForwardEmail, user.ProperName, rq.Title, cvs.ShortID, m.Content);
                    UserUtility.NotifyEmail(format, dicmes);

                    if (!string.IsNullOrWhiteSpace(contentMessage))
                    {
                        format = _EmailFormatService.GetById(Convert.ToInt32(Resources.Resource.NotifyEmailForwardMessage));
                        dicmes = new DictionaryForwardMessage(rq.ForwardEmail, user.ProperName, rq.Title, cvs.ShortID, lastmes.Content);
                        UserUtility.NotifyEmail(format, dicmes);
                    }
                }
                catch (Exception) { }

                try
                {
                    format = _EmailFormatService.GetById(Convert.ToInt32(Resources.Resource.NotifyEmailForwardBidding));
                    dic = new DictionaryMessageBid(rq.ForwardEmail, user.ProperName, rq.Title, cvs.ShortID, o.PriceBid.ToString());
                    UserUtility.NotifyEmail(format, dic);
                }
                catch (Exception) { }
            }

            var uSms = _UserService.GetById(sellerID);
            if (uSms != null && uSms.Premium && uSms.Phone != null)
            {
                SmsHelpers smsHelper = new SmsHelpers();
                string messid = "sms_" + o.ID + "_" + "BidRequestSms";
                string smsresult = "";
                string smsContent = Resources.Resource.SmsBidRequestContent.Replace("{buyer}", StringHanding.Convert(user.ProperName)).Replace("{title}", StringHanding.Convert(rq.Title)).Replace("{price}", o.PriceBid.ToString());
                var smsResultObj = smsHelper.Send(messid, uSms.Phone, smsContent, out smsresult);
                _SmsLogService.Add(new SmsLog()
                {
                    DateCreated = DateTime.Now,
                    MessageID = smsResultObj.message_id,
                    SmsResult = smsresult,
                    Status = smsResultObj.status,
                    UserID = uSms.ID,
                    BidRequestID = o.ID,
                    SmsContent = smsContent
                });
            }
            return Json(new { sellerID = sellerID, buyerId = user.ID, buyerName = user.ProperName });
        }

        public ActionResult SaveOrderRequest(int orderid, string contentMessage)
        {
            if (!User.Identity.IsAuthenticated) return RedirectToAction("index", "home");
            var user = UtilityService.GetLoginUser(_UserService, User);
            var o = _OrderService.GetById(orderid);
            if (!string.IsNullOrWhiteSpace(contentMessage))
            {
                MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, contentMessage, MessageHelper.BuildShortIDOrder(o.ID), OrderHelper.GetWorkerID(o), OrderHelper.GetPayerID(o), (int)MessageType.ORDER_REQUEST, null);
                var unread = _MMessageService.CountUnread(OrderHelper.GetWorkerID(o));
                MessageHelper.SendMessageNotifyMessage(_MMessageService, Resources.Resource.SystemNotifyQuestion, unread, Resources.Resource.NumberMessageToNotify, OrderHelper.GetWorkerID(o), false);
            }
            return Json(new { sellerID = OrderHelper.GetWorkerID(o), buyerId = user.ID, buyerName = user.ProperName });
            //return RedirectToAction("Details", "Request", new { id = o.RequestID });
        }

        public ActionResult FakeOrderRequest(int bidid)
        {
            var b = _BidRequestService.GetById(bidid);
            TempData["bidid"] = bidid;
            TempData["issuccess"] = true;
            return RedirectToAction("Details", "Request", new { id = b.RequestID });
        }

        public ActionResult Details(int id)
        {
            if (!User.Identity.IsAuthenticated) return RedirectToAction("Index", "Home");
            var user = UtilityService.GetLoginUser(_UserService, User);
            var cvsid = MessageHelper.BuildShortIDOrder(id);
            var order = _OrderService.GetById(id);
            if (user.ID != order.BuyerID && user.ID != order.SellerID) return HttpNotFound("Cannot access.");

            var current = DateTime.Now;
            if (!order.DisableDetails && order.Status == (int)OrderStatusV2.InProgress)
            {
                var remain = (DateTime)(order.Deadline ?? DateTime.Now) - current;
                if (remain.TotalDays < -3)
                {
                    order.Status = (int)OrderStatusV2.Failed;
                    order.Rate = 1;
                    order.Comment = Resources.Resource.SystemCommentFailedOrder;
                    order.ModifiedDate = current;
                    _OrderService.Update(order);
                }
            }
            else if (!order.DisableDetails && order.Status == (int)OrderStatusV2.WaitDone)
            {
                var remain = order.ModifiedDate - current;
                if (remain.TotalDays < -3)
                {
                    order.Status = (int)OrderStatusV2.Done;
                    order.ModifiedDate = current;
                    _OrderService.Update(order);
                }
            }

            if (order.Type == (int)OrderType.PROVIDE)
            {
                order.Provide = _ProvideService.GetById(order.ProvideID);
            }
            else
            {
                order.Request = _RequestService.GetById(order.RequestID);
            }
            var cvs = _MConversationService.GetConversationByShortID(cvsid);
            cvs.Messages = _MMessageService.GetMessagesByShortID(cvs.ShortID);
            var model = cvs;
            foreach (var item in model.Messages)
            {
                if (item.ReceiverID == user.ID)
                {
                    if (!item.IsRead)
                    {
                        item.IsRead = true;
                        _MMessageService.UpdateStatusMessage(item);
                    }
                }
            }
            ViewData["curuserid"] = user.ID;
            ViewData["displayorder"] = order;
            if (TempData["issuccess"] != null)
            {
                ViewData["issuccess"] = TempData["issuccess"];
                if (!Convert.ToBoolean(TempData["issuccess"]))
                {
                    ViewData["result"] = TempData["result"];
                }
            }
            return View(model);
        }

        public ActionResult MakeAcceptOrder(int orderid)
        {
            if (!User.Identity.IsAuthenticated) return Json(new { result = false });
            var user = UtilityService.GetLoginUser(_UserService, User);
            var order = _OrderService.GetById(orderid);
            if (order == null) return Json(new { result = false });
            order.StartedDate = DateTime.Now;
            order.Deadline = DateTime.Now.AddDays(order.TimeToFinish);
            order.Status = (int)OrderStatusV2.InProgress;
            order.ModifiedDate = DateTime.Now;
            _OrderService.Update(order);
            var m = new MMessage()
            {
                Content = Resources.Resource.SystemMessageAcceptOrder,
                Date = DateTime.Now,
                Info = new MMessageEmbedInfo()
                {
                    Type = (int)EEmbedInfoType.Accept
                },
                IsRead = false,
                ParentID = MessageHelper.BuildShortIDOrder(order.ID),
                ReceiverID = (order.SellerID == user.ID ? order.BuyerID : order.SellerID),
                SenderID = user.ID,
                Type = (int)(order.Type == (int)OrderType.PROVIDE ? MessageType.ORDER_PROVIDE : MessageType.ORDER_REQUEST)
            };
            _MMessageService.Add(m);
            MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, m.Content, MessageHelper.BuildShortIDNotify(m.ParentID), m.ReceiverID, m.SenderID, (int)MessageType.System_Notify, m.Info);
            return Json(new { result = true });
        }

        public ActionResult MakeDeliveryOrder(int orderid, string linkresult, HttpPostedFileBase file, HttpPostedFileBase filedemo)
        {
            if (!User.Identity.IsAuthenticated) return Json(new { result = false });
            var user = UtilityService.GetLoginUser(_UserService, User);
            var order = _OrderService.GetById(orderid);
            if (order == null) return Json(new { result = false });
            var allow = (order.PaymentStatus == (int)EPaymentStatus.Finish_Payment);
            String delivery = "";
            String deliverydemo = "";
            String meserrordelivery = "";
            String meserrordemo = "";
            if (file != null && file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);
                fileName = UploadHelper.GetNamePlusDatetime(fileName, true);
                var path = Path.Combine(UploadHelper.GetPathSaveFile(user.ID), fileName);
                if (file.ContentLength > (1024 * 1024 * 200))
                {
                    meserrordelivery = "Tập tin kết quả vượt quá dung lượng cho phép.";
                }
                else
                {
                    file.SaveAs(path);
                    delivery = fileName;
                }
            }

            if (filedemo != null && filedemo.ContentLength > 0)
            {
                var fileName = Path.GetFileName(filedemo.FileName);
                fileName = UploadHelper.GetNamePlusDatetime(fileName, true);
                var path = Path.Combine(UploadHelper.GetPathSaveFile(user.ID), fileName);
                if (file.ContentLength > (1024 * 1024 * 200))
                {
                    meserrordemo = "Tập tin demo vượt quá dung lượng cho phép.";
                }
                else
                {
                    file.SaveAs(path);
                    deliverydemo = fileName;
                }
            }
            if (!string.IsNullOrWhiteSpace(meserrordelivery) || !string.IsNullOrWhiteSpace(meserrordemo))
            {
                return Json(new { result = false, mes1 = meserrordelivery, mes2 = meserrordemo });
            }
            var m = new MMessage()
            {
                Content = (string.IsNullOrWhiteSpace(linkresult) ? Resources.Resource.SystemMessageDeliveryOrder : linkresult),
                Date = DateTime.Now,
                Info = new MMessageEmbedInfo()
                {
                    Type = (int)EEmbedInfoType.Delivery,
                    Download = (string.IsNullOrWhiteSpace(delivery) ? null : UploadHelper.GetLinkDownload(user.ID, delivery, OrderHelper.GetPayerID(order), order.ID)),
                    AllowDownload = allow,
                    Demo = (string.IsNullOrWhiteSpace(deliverydemo) ? null : UploadHelper.GetLinkDownload(user.ID, deliverydemo, OrderHelper.GetPayerID(order), order.ID))
                },
                IsRead = false,
                ParentID = MessageHelper.BuildShortIDOrder(order.ID),
                ReceiverID = (order.SellerID == user.ID ? order.BuyerID : order.SellerID),
                SenderID = user.ID,
                Type = (int)(order.Type == (int)OrderType.PROVIDE ? MessageType.ORDER_PROVIDE : MessageType.ORDER_REQUEST)
            };
            _MMessageService.Add(m);
            MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService,Resources.Resource.SystemMessageDeliveryOrder, MessageHelper.BuildShortIDNotify(m.ParentID), m.ReceiverID, m.SenderID, (int)MessageType.System_Notify, m.Info);
            order.Status = (int)OrderStatusV2.WaitDone;
            order.ModifiedDate = DateTime.Now;
            _OrderService.Update(order);
            return Json(new { result = true });
        }

        public ActionResult MakeRejectOrder(int orderid)
        {
            if (!User.Identity.IsAuthenticated) return Json(new { result = false });
            var user = UtilityService.GetLoginUser(_UserService, User);
            var order = _OrderService.GetById(orderid);
            if (order == null) return Json(new { result = false });
            order.Status = (int)OrderStatusV2.Rejected;
            order.ModifiedDate = DateTime.Now;
            _OrderService.Update(order);
            var m = new MMessage()
            {
                Content = Resources.Resource.SystemMessageRejectOrder,
                Date = DateTime.Now,
                Info = new MMessageEmbedInfo()
                {
                    Type = (int)EEmbedInfoType.Rejected
                },
                IsRead = false,
                ParentID = MessageHelper.BuildShortIDOrder(order.ID),
                ReceiverID = (order.SellerID == user.ID ? order.BuyerID : order.SellerID),
                SenderID = user.ID,
                Type = (int)(order.Type == (int)OrderType.PROVIDE ? MessageType.ORDER_PROVIDE : MessageType.ORDER_REQUEST)
            };
            _MMessageService.Add(m);
            MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, m.Content, MessageHelper.BuildShortIDNotify(m.ParentID), m.ReceiverID, m.SenderID, (int)MessageType.System_Notify, m.Info);
            return Json(new { result = true });
        }

        public ActionResult MakeDoneOrder(int orderid)
        {
            if (!User.Identity.IsAuthenticated) return Json(new { result = false });
            var user = UtilityService.GetLoginUser(_UserService, User);
            var order = _OrderService.GetById(orderid);
            if (order == null) return Json(new { result = false });
            order.Status = (int)OrderStatusV2.Done;
            order.ModifiedDate = DateTime.Now;
            _OrderService.Update(order);
                     Provide provide=null;
            Request request=null;
            if(order.Type==(int)OrderType.PROVIDE){
             provide=   _ProvideService.GetById(order.ProvideID);
            }
            else{
              request=_RequestService.GetById(order.RequestID);
            }
            var format = Resources.Resource.SystemNotifyMessageOrderDone;
            var dic = new DictionaryOrderDone(UserUtility.GetVerifiedEmail(user), user.ProperName, (provide == null ? request.Title : provide.Title), order.ID.ToString(), MessageHelper.BuildShortIDOrder(order.ID), (provide == null ? request.ID.ToString() : provide.ID.ToString()));
            var content = MessageHelper.BuildNotifyMessageContent(format, dic);

            MessageHelper.SendMessage(_UserService, _MConversationService, _MMessageService, content, MessageHelper.BuildShortIDNotify(MessageHelper.BuildShortIDOrder(order.ID)), OrderHelper.GetWorkerID(order), user.ID, (int)MessageType.System_Notify,null);
            return Json(new { result = true });
        }

        public ActionResult ManageOrder()
        {
            if (!User.Identity.IsAuthenticated) return RedirectToAction("Index", "Home");
            var user = UtilityService.GetLoginUser(_UserService, User);
            var orders = _OrderService.GetAllOrderPayer(user.ID);
            foreach (var item in orders)
            {
                if (item.SellerID == user.ID)
                {
                    item.Seller = user;
                    item.Buyer = _UserService.GetById(item.BuyerID);
                }
                else
                {
                    item.Seller = _UserService.GetById(item.SellerID);
                    item.Buyer = user;
                }
                if (item.Type == (int)OrderType.PROVIDE)
                {
                    item.Provide = _ProvideService.GetById(item.ProvideID);
                }
                else
                {
                    item.Request = _RequestService.GetById(item.RequestID);
                }
            }
            List<int> lstdone = new List<int>();
            lstdone.Add((int)OrderStatusV2.Done);
            lstdone.Add((int)OrderStatusV2.Failed);
            lstdone.Add((int)OrderStatusV2.Cancel);
            ViewData["waitdone"] = orders.Where(o => !lstdone.Contains(o.Status)).ToList();
            ViewData["done"] = orders.Where(o => lstdone.Contains(o.Status)).ToList();
            ViewData["user"] = user;
            ViewData["statisticwaitaccept"] = orders.Where(o => o.Status == (int)OrderStatusV2.WaitProgress).Count();
            ViewData["statisticwaitdone"] = orders.Where(o => o.Status == (int)OrderStatusV2.WaitDone).Count();
            ViewData["statisticprocess"] = orders.Where(o => o.Status == (int)OrderStatusV2.InProgress || o.Status == (int)OrderStatusV2.Rejected).Count();
            ViewData["statisticdone"] = orders.Where(o => o.Status == (int)OrderStatusV2.Done).Count();
            ViewData["statisticcancel"] = orders.Where(o => o.Status == (int)OrderStatusV2.Failed || o.Status == (int)OrderStatusV2.Cancel).Count();
            int totalmoney = 0;
            foreach (var item in orders.Where(o => o.Status == (int)OrderStatusV2.Done && !o.DisableDetails).ToList())
            {
                totalmoney += item.Price;
            }
            ViewData["totalmoney"] = totalmoney;
            return View();
        }

        public ActionResult ManageService()
        {
            if (!User.Identity.IsAuthenticated) return RedirectToAction("Index", "Home");
            var user = UtilityService.GetLoginUser(_UserService, User);
            var orders = _OrderService.GetAllOrderWorker(user.ID);
            foreach (var item in orders)
            {
                if (item.SellerID == user.ID)
                {
                    item.Seller = user;
                    item.Buyer = _UserService.GetById(item.BuyerID);
                }
                else
                {
                    item.Seller = _UserService.GetById(item.SellerID);
                    item.Buyer = user;
                }
                if (item.Type == (int)OrderType.PROVIDE)
                {
                    item.Provide = _ProvideService.GetById(item.ProvideID);
                }
                else
                {
                    item.Request = _RequestService.GetById(item.RequestID);
                }
            }
            List<int> lstdone = new List<int>();
            lstdone.Add((int)OrderStatusV2.Done);
            lstdone.Add((int)OrderStatusV2.Failed);
            lstdone.Add((int)OrderStatusV2.Cancel);
            ViewData["waitdone"] = orders.Where(o => !lstdone.Contains(o.Status)).ToList();
            ViewData["done"] = orders.Where(o => lstdone.Contains(o.Status)).ToList();
            var test = ViewData["waitdone"] as List<Order>;
            ViewData["user"] = user;
            ViewData["statisticwaitaccept"] = orders.Where(o => o.Status == (int)OrderStatusV2.WaitProgress).Count();
            ViewData["statisticwaitdone"] = orders.Where(o => o.Status == (int)OrderStatusV2.WaitDone).Count();
            ViewData["statisticprocess"] = orders.Where(o => o.Status == (int)OrderStatusV2.InProgress || o.Status == (int)OrderStatusV2.Rejected).Count();
            ViewData["statisticdone"] = orders.Where(o => o.Status == (int)OrderStatusV2.Done).Count();
            ViewData["statisticcancel"] = orders.Where(o => o.Status == (int)OrderStatusV2.Failed || o.Status == (int)OrderStatusV2.Cancel).Count();
            int totalmoney = 0;
            foreach (var item in orders.Where(o => o.Status == (int)OrderStatusV2.Done && !o.DisableDetails).ToList())
            {
                totalmoney += item.Price;
            }
            ViewData["totalmoney"] = totalmoney;
            return View();
        }


        public ActionResult GetCountServiceProcess()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return Json(0);
            }
            var user = _UserService.GetByFBID(User.Identity.Name) ?? _UserService.GetByEmail(User.Identity.Name);
            var count = _OrderService.CountServiceProcess(user.ID);
            return Json(count);
        }

        public ActionResult GetCountOrderWaitDone()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return Json(0);
            }
            var user = _UserService.GetByFBID(User.Identity.Name) ?? _UserService.GetByEmail(User.Identity.Name);
            var count = _OrderService.CountOrderWaitDone(user.ID);
            return Json(count);
        }

        public ActionResult CommentOrder(int orderid, string comment)
        {
            if (!User.Identity.IsAuthenticated) return Json(new { result = false });
            var user = UtilityService.GetLoginUser(_UserService, User);
            var order = _OrderService.GetById(orderid);
            if (order == null) return Json(new { result = false });
            order.Comment = comment;
            order.ModifiedDate = DateTime.Now;
            _OrderService.Update(order);
            var orders = MemCache.Get<List<Order>>("user_comment_" + user.ID);
            if (orders != null)
            {
                order.Buyer = _UserService.GetById(order.BuyerID);
                orders.Add(order);
                orders = orders.OrderByDescending(o => o.ModifiedDate).ToList();
                MemCache.InsertCache("user_comment_" + order.SellerID, orders);
            }
            return Json(new { result = true });
        }

        public ActionResult RateOrder(int orderid, string rate)
        {
            if (!User.Identity.IsAuthenticated) return Json(new { result = false });
            var order = _OrderService.GetById(orderid);
            if (order == null) return Json(new { result = false });
            order.Rate = Convert.ToByte(rate);
            order.ModifiedDate = DateTime.Now;
            _OrderService.Update(order);
            return Json(new { result = true });
        }
    }
}